{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Introduction to Claude Skills\n\nLearn how to use Claude's Skills feature to create professional documents, analyze data, and automate business workflows with Excel, PowerPoint, and PDF generation.\n\n> **See it in action:** The Skills you'll learn about power Claude's file creation capabilities! Check out **[Claude Creates Files](https://www.anthropic.com/news/create-files)** to see how these Skills enable Claude to create and edit documents directly in Claude.ai."
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Table of Contents\n",
    "\n",
    "1. [Setup & Installation](#setup)\n",
    "2. [Understanding Skills](#understanding)\n",
    "3. [Discovering Available Skills](#discovering)\n",
    "4. [Quick Start: Excel](#excel-quickstart)\n",
    "5. [Quick Start: PowerPoint](#powerpoint-quickstart)\n",
    "6. [Quick Start: PDF](#pdf-quickstart)\n",
    "7. [Troubleshooting](#troubleshooting)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 1. Setup & Installation {#setup}\n\n### Prerequisites\n\nBefore starting, make sure you have:\n- Python 3.8 or higher\n- An Anthropic API key from [console.anthropic.com](https://console.anthropic.com/)\n\n### Environment Setup (First Time Only)\n\n**If you haven't set up your environment yet**, follow these steps:\n\n#### Step 1: Create Virtual Environment\n\n```bash\n# Navigate to the skills directory\ncd /path/to/claude-cookbooks/skills\n\n# Create virtual environment\npython -m venv venv\n\n# Activate it\nsource venv/bin/activate  # On macOS/Linux\n# OR\nvenv\\Scripts\\activate     # On Windows\n```\n\n#### Step 2: Install Dependencies\n\n```bash\n# With venv activated, install requirements\npip install -r requirements.txt\n```\n\n#### Step 3: Select Kernel in VSCode/Jupyter\n\n**In VSCode:**\n1. Open this notebook\n2. Click the kernel picker in the top-right (e.g., \"Python 3.11.x\")\n3. Select \"Python Environments...\"\n4. Choose the `./venv/bin/python` interpreter\n\n**In Jupyter:**\n1. From the Kernel menu → Change Kernel\n2. Select the kernel matching your venv\n\n#### Step 4: Configure API Key\n\n```bash\n# Copy the example file\ncp .env.example .env\n\n# Edit .env and add your API key:\n# ANTHROPIC_API_KEY=sk-ant-api03-...\n```\n\n### Quick Installation Check\n\nRun the cell below to verify your environment is set up correctly:"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**If you see any ❌ or ⚠️ warnings above**, please complete the setup steps before continuing.\n\n**If anthropic SDK version is too old (needs 0.71.0 or later):**\n```bash\npip install anthropic>=0.71.0\n```\nThen **restart the Jupyter kernel** to pick up the new version.\n\n---\n\n### API Configuration\n\nNow let's load the API key and configure the client:"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### API Configuration\n",
    "\n",
    "**⚠️ Important**: Create a `.env` file in the skills directory:\n",
    "\n",
    "```bash\n",
    "# Copy the example file\n",
    "cp ../.env.example ../.env\n",
    "```\n",
    "\n",
    "Then edit `../.env` to add your Anthropic API key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "# Add parent directory to path for imports\n",
    "sys.path.insert(0, str(Path.cwd().parent))\n",
    "\n",
    "\n",
    "from anthropic import Anthropic\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "# Import our file utilities\n",
    "from file_utils import (\n",
    "    download_all_files,\n",
    "    extract_file_ids,\n",
    "    get_file_info,\n",
    "    print_download_summary,\n",
    ")\n",
    "\n",
    "# Load environment variables from parent directory\n",
    "load_dotenv(Path.cwd().parent / \".env\")\n",
    "\n",
    "API_KEY = os.getenv(\"ANTHROPIC_API_KEY\")\n",
    "MODEL = os.getenv(\"ANTHROPIC_MODEL\", \"claude-sonnet-4-5\")\n",
    "\n",
    "if not API_KEY:\n",
    "    raise ValueError(\n",
    "        \"ANTHROPIC_API_KEY not found. Copy ../.env.example to ../.env and add your API key.\"\n",
    "    )\n",
    "\n",
    "# Initialize client\n",
    "# Note: We'll add beta headers per-request when using Skills\n",
    "client = Anthropic(api_key=API_KEY)\n",
    "\n",
    "# Create outputs directory if it doesn't exist\n",
    "OUTPUT_DIR = Path.cwd().parent / \"outputs\"\n",
    "OUTPUT_DIR.mkdir(exist_ok=True)\n",
    "\n",
    "print(\"✓ API key loaded\")\n",
    "print(f\"✓ Using model: {MODEL}\")\n",
    "print(f\"✓ Output directory: {OUTPUT_DIR}\")\n",
    "print(\"\\n📝 Note: Beta headers will be added per-request when using Skills\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Test Connection\n",
    "\n",
    "Let's verify our API connection works:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Simple test to verify API connection\n",
    "test_response = client.messages.create(\n",
    "    model=MODEL,\n",
    "    max_tokens=100,\n",
    "    messages=[\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"Say 'Connection successful!' if you can read this.\",\n",
    "        }\n",
    "    ],\n",
    ")\n",
    "\n",
    "print(\"API Test Response:\")\n",
    "print(test_response.content[0].text)\n",
    "print(\n",
    "    f\"\\n✓ Token usage: {test_response.usage.input_tokens} in, {test_response.usage.output_tokens} out\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 2. Understanding Skills {#understanding}\n\n### What are Skills?\n\n**Skills** are organized packages of instructions, executable code, and resources that give Claude specialized capabilities for specific tasks. Think of them as \"expertise packages\" that Claude can discover and load dynamically.\n\n📖 Read our engineering blog post on [Equipping agents for the real world with Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills)\n\n### Why Skills Matter\n\nAfter learning about MCPs (Model Context Protocol) and tools, you might wonder why Skills are important:\n\n- **Skills are higher-level** than individual tools - they combine instructions, code, and resources\n- **Skills are composable** - multiple skills work together seamlessly\n- **Skills are efficient** - progressive disclosure means you only pay for what you use\n- **Skills include proven code** - helper scripts that work reliably, saving time and reducing errors\n\n### Key Benefits\n\n- **Expert-level Performance**: Deliver professional results without the learning curve\n- **Proven Helper Scripts**: Skills contain tested, working code that Claude can use immediately\n- **Organizational Knowledge**: Package company workflows and best practices\n- **Cost Efficiency**: Progressive disclosure minimizes token usage\n- **Reliability**: Pre-tested scripts mean fewer errors and consistent results\n- **Time Savings**: Claude uses existing solutions instead of generating code from scratch\n- **Composable**: Multiple skills work together for complex workflows\n\n### Progressive Disclosure Architecture\n\nSkills use a three-tier loading model:\n\n![Progressive Disclosure - How Skills Load](../assets/prog-disc-1.png)\n\n1. **Metadata** (name: 64 chars, description: 1024 chars): Claude sees skill name and description\n2. **Full Instructions** (<5k tokens): Loaded when skill is relevant\n3. **Linked Files**: Additional resources loaded only if needed\n\n![Progressive Disclosure Stages](../assets/prog-disc-2.png)\n\nThis keeps operations efficient while providing deep expertise on demand. Initially, Claude sees just the metadata from the YAML frontmatter of SKILL.md. Only when a skill is relevant does Claude load the full contents, including any helper scripts and resources.\n\n### Skill Types\n\n| Type | Description | Example |\n|------|-------------|----------|\n| **Anthropic-Managed** | Pre-built skills maintained by Anthropic | `xlsx`, `pptx`, `pdf`, `docx` |\n| **Custom** | User-defined skills for specific workflows | Brand guidelines, financial models |"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Skills Conceptual Overview\n\n![Skills Conceptual Diagram](../assets/skills-conceptual-diagram.png)\n\nThis diagram illustrates:\n- **Skill Directory Structure**: How Skills are organized with SKILL.md and supporting files\n- **YAML Frontmatter**: The metadata that Claude sees initially\n- **Progressive Loading**: How Skills are discovered and loaded on-demand\n- **Composability**: Multiple Skills working together in a single request"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How Skills Work with Code Execution\n",
    "\n",
    "Skills require the **code execution** tool to be enabled. Here's the typical workflow:\n",
    "\n",
    "```python\n",
    "# Use client.beta.messages.create() for Skills support\n",
    "response = client.beta.messages.create(\n",
    "    model=\"claude-sonnet-4-5\",\n",
    "    max_tokens=4096,\n",
    "    container={\n",
    "        \"skills\": [\n",
    "            {\"type\": \"anthropic\", \"skill_id\": \"xlsx\", \"version\": \"latest\"}\n",
    "        ]\n",
    "    },\n",
    "    tools=[{\"type\": \"code_execution_20250825\", \"name\": \"code_execution\"}],\n",
    "    messages=[{\"role\": \"user\", \"content\": \"Create an Excel file...\"}],\n",
    "    # Use betas parameter instead of extra_headers\n",
    "    betas=[\"code-execution-2025-08-25\", \"files-api-2025-04-14\", \"skills-2025-10-02\"]\n",
    ")\n",
    "```\n",
    "\n",
    "**What happens:**\n",
    "1. Claude receives your request with the xlsx skill loaded\n",
    "2. Claude uses code execution to create the file\n",
    "3. The response includes a `file_id` for the created file\n",
    "4. You use the **Files API** to download the file\n",
    "\n",
    "**Important: Beta API**\n",
    "- Use `client.beta.messages.create()` (not `client.messages.create()`)\n",
    "- The `container` parameter is only available in the beta API\n",
    "- Use the `betas` parameter to enable beta features:\n",
    "  - `code-execution-2025-08-25` - Enables code execution\n",
    "  - `files-api-2025-04-14` - Required for downloading files\n",
    "  - `skills-2025-10-02` - Enables Skills feature\n",
    "\n",
    "⚠️ **Note**: When using Skills, you MUST include the code_execution tool in your request."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Token Usage Optimization\n",
    "\n",
    "Skills dramatically reduce token usage compared to providing instructions in prompts:\n",
    "\n",
    "| Approach | Token Cost | Performance |\n",
    "|----------|------------|-------------|\n",
    "| Manual instructions | 5,000-10,000 tokens/request | Variable quality |\n",
    "| Skills (metadata only) | Minimal (just name/description) | Expert-level |\n",
    "| Skills (full load) | ~5,000 tokens when skill is used | Expert-level |\n",
    "\n",
    "**The Big Win:** You can pack multiple skills into your prompt without bloating it. Each skill only costs you the metadata (name + description) until you actually use it.\n",
    "\n",
    "**Example**: Creating an Excel file with formatting\n",
    "- Without Skills: ~8,000 tokens to explain all Excel features upfront\n",
    "- With Skills: Minimal metadata overhead initially, ~5,000 tokens only when Excel skill is invoked\n",
    "- **Key Insight**: The 98% savings applies to the initial context. Once you use a skill, the full instructions are loaded.\n",
    "\n",
    "**Additional Benefits:**\n",
    "- Skills contain helper scripts that are known to work, improving reliability\n",
    "- Claude saves time by using proven code patterns instead of generating from scratch\n",
    "- You get more consistent, professional results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ⏱️ Expected Generation Times\n",
    "\n",
    "**⚠️ IMPORTANT**: Document generation with Skills requires code execution and file creation, which takes time. Be patient and let cells complete.\n",
    "\n",
    "**Observed generation times:**\n",
    "- **Excel files**: ~2 minutes (with charts and formatting)\n",
    "- **PowerPoint presentations**: ~1-2 minutes (simple 2-slide presentations with charts)\n",
    "- **PDF documents**: ~40-60 seconds (simple documents)\n",
    "\n",
    "**What to expect:**\n",
    "- The cell will show `[*]` while running\n",
    "- You may see \"Executing...\" status for 1-2 minutes\n",
    "- **Do not interrupt the cell** - let it complete fully\n",
    "\n",
    "**💡 Recommendations:**\n",
    "1. **Start simple**: Begin with minimal examples to verify your setup\n",
    "2. **Gradually increase complexity**: Add features incrementally\n",
    "3. **Be patient**: Operations typically take 40 seconds to 2 minutes\n",
    "4. **Note**: Very complex documents may take longer - keep examples focused"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Discovering Available Skills {#discovering}\n",
    "\n",
    "### List All Built-in Skills\n",
    "\n",
    "Let's discover what Anthropic-managed skills are available:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# List all available Anthropic skills\n",
    "# Note: Skills API requires the skills beta header\n",
    "client_with_skills_beta = Anthropic(\n",
    "    api_key=API_KEY, default_headers={\"anthropic-beta\": \"skills-2025-10-02\"}\n",
    ")\n",
    "\n",
    "skills_response = client_with_skills_beta.beta.skills.list(source=\"anthropic\")\n",
    "\n",
    "print(\"Available Anthropic-Managed Skills:\")\n",
    "print(\"=\" * 80)\n",
    "\n",
    "for skill in skills_response.data:\n",
    "    print(f\"\\n📦 Skill ID: {skill.id}\")\n",
    "    print(f\"   Title: {skill.display_title}\")\n",
    "    print(f\"   Latest Version: {skill.latest_version}\")\n",
    "    print(f\"   Created: {skill.created_at}\")\n",
    "\n",
    "    # Get version details\n",
    "    try:\n",
    "        version_info = client_with_skills_beta.beta.skills.versions.retrieve(\n",
    "            skill_id=skill.id, version=skill.latest_version\n",
    "        )\n",
    "        print(f\"   Name: {version_info.name}\")\n",
    "        print(f\"   Description: {version_info.description}\")\n",
    "    except Exception as e:\n",
    "        print(f\"   (Unable to fetch version details: {e})\")\n",
    "\n",
    "print(f\"\\n\\n✓ Found {len(skills_response.data)} Anthropic-managed skills\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Understanding Skill Metadata\n",
    "\n",
    "Each skill has:\n",
    "- **skill_id**: Unique identifier (e.g., \"xlsx\", \"pptx\")\n",
    "- **version**: Version number or \"latest\"\n",
    "- **name**: Human-readable name\n",
    "- **description**: What the skill does\n",
    "- **directory**: Skill's folder structure\n",
    "\n",
    "### Versioning Strategy\n",
    "\n",
    "- Use `\"latest\"` for Anthropic skills (recommended)\n",
    "- Anthropic updates skills automatically\n",
    "- Pin specific versions for production stability\n",
    "- Custom skills use epoch timestamps for versions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: Monthly Budget Spreadsheet\n",
    "\n",
    "We'll start with two examples - a simple one-liner and a detailed request.\n",
    "\n",
    "#### Simple Example (1-2 lines)\n",
    "First, let's see how Skills work with a minimal prompt:\n",
    "\n",
    "```python\n",
    "# Simple prompt - Skills handle the complexity\n",
    "prompt = \"Create a quarterly sales report Excel file with revenue data and a chart\"\n",
    "```\n",
    "\n",
    "#### Detailed Example\n",
    "For more control, you can provide specific requirements:\n",
    "- Income and expense categories\n",
    "- Formulas for totals\n",
    "- Basic formatting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: Monthly Budget Spreadsheet\n",
    "\n",
    "We'll create a simple budget spreadsheet with:\n",
    "- Income and expense categories\n",
    "- Formulas for totals\n",
    "- Basic formatting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**⏱️ Note**: Excel generation typically takes **1-2 minutes** (with charts and formatting). The cell will show `[*]` while running - be patient!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an Excel budget spreadsheet\n",
    "excel_response = client.beta.messages.create(  # Note: Using beta.messages for Skills support\n",
    "    model=MODEL,\n",
    "    max_tokens=4096,\n",
    "    container={\"skills\": [{\"type\": \"anthropic\", \"skill_id\": \"xlsx\", \"version\": \"latest\"}]},\n",
    "    tools=[{\"type\": \"code_execution_20250825\", \"name\": \"code_execution\"}],\n",
    "    messages=[\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"\"\"Create a monthly budget Excel spreadsheet with the following:\n",
    "\n",
    "Income:\n",
    "- Salary: $5,000\n",
    "- Freelance: $1,200\n",
    "- Investments: $300\n",
    "\n",
    "Expenses:\n",
    "- Rent: $1,500\n",
    "- Utilities: $200\n",
    "- Groceries: $600\n",
    "- Transportation: $300\n",
    "- Entertainment: $400\n",
    "- Savings: $1,000\n",
    "\n",
    "Include:\n",
    "1. Formulas to calculate total income and total expenses\n",
    "2. A formula for net savings (income - expenses)\n",
    "3. Format currency values properly\n",
    "4. Add a simple column chart showing income vs expenses\n",
    "5. Use professional formatting with headers\n",
    "\"\"\",\n",
    "        }\n",
    "    ],\n",
    "    # Use betas parameter for beta features\n",
    "    betas=[\"code-execution-2025-08-25\", \"files-api-2025-04-14\", \"skills-2025-10-02\"],\n",
    ")\n",
    "\n",
    "print(\"Excel Response:\")\n",
    "print(\"=\" * 80)\n",
    "for content in excel_response.content:\n",
    "    if content.type == \"text\":\n",
    "        print(content.text)\n",
    "    elif content.type == \"tool_use\":\n",
    "        print(f\"\\n🔧 Tool: {content.name}\")\n",
    "        if hasattr(content, \"input\"):\n",
    "            print(f\"   Input preview: {str(content.input)[:200]}...\")\n",
    "\n",
    "print(\"\\n\\n📊 Token Usage:\")\n",
    "print(f\"   Input: {excel_response.usage.input_tokens}\")\n",
    "print(f\"   Output: {excel_response.usage.output_tokens}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download the Excel File\n",
    "\n",
    "Now let's extract the file_id and download the generated Excel file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Extract file IDs from the response\n",
    "file_ids = extract_file_ids(excel_response)\n",
    "\n",
    "if file_ids:\n",
    "    print(f\"✓ Found {len(file_ids)} file(s)\\n\")\n",
    "\n",
    "    # Download all files\n",
    "    results = download_all_files(\n",
    "        client, excel_response, output_dir=str(OUTPUT_DIR), prefix=\"budget_\"\n",
    "    )\n",
    "\n",
    "    # Print summary\n",
    "    print_download_summary(results)\n",
    "\n",
    "    # Show file details\n",
    "    for file_id in file_ids:\n",
    "        info = get_file_info(client, file_id)\n",
    "        if info:\n",
    "            print(\"\\n📄 File Details:\")\n",
    "            print(f\"   Filename: {info['filename']}\")\n",
    "            print(f\"   Size: {info['size'] / 1024:.1f} KB\")\n",
    "            print(f\"   Created: {info['created_at']}\")\n",
    "else:\n",
    "    print(\"❌ No files found in response\")\n",
    "    print(\"\\nDebug: Response content types:\")\n",
    "    for i, content in enumerate(excel_response.content):\n",
    "        print(f\"  {i}. {content.type}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**✨ What just happened?**\n",
    "\n",
    "1. Claude used the `xlsx` skill to create a professional Excel file\n",
    "2. The skill handled all Excel-specific formatting and formulas\n",
    "3. The file was created in Claude's code execution environment\n",
    "4. We extracted the `file_id` from the response\n",
    "5. We downloaded the file using the Files API\n",
    "6. The file is now saved in `outputs/budget_*.xlsx`\n",
    "\n",
    "Open the file in Excel to see the results!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Quick Start: PowerPoint {#powerpoint-quickstart}\n",
    "\n",
    "Now let's create a PowerPoint presentation using the `pptx` skill."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: Revenue Presentation\n",
    "\n",
    "#### Simple Example (1 line)\n",
    "```python\n",
    "# Minimal prompt - let Skills handle the details\n",
    "prompt = \"Create an executive summary presentation with 3 slides about Q3 results\"\n",
    "```\n",
    "\n",
    "#### Detailed Example\n",
    "**Note**: This is intentionally kept simple (2 slides, 1 chart) to minimize generation time and demonstrate the core functionality."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: Simple Revenue Presentation\n",
    "\n",
    "**Note**: This is intentionally kept simple (2 slides, 1 chart) to minimize generation time and demonstrate the core functionality."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a PowerPoint presentation\n",
    "pptx_response = client.beta.messages.create(\n",
    "    model=MODEL,\n",
    "    max_tokens=4096,\n",
    "    container={\"skills\": [{\"type\": \"anthropic\", \"skill_id\": \"pptx\", \"version\": \"latest\"}]},\n",
    "    tools=[{\"type\": \"code_execution_20250825\", \"name\": \"code_execution\"}],\n",
    "    messages=[\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"\"\"Create a simple 2-slide PowerPoint presentation:\n",
    "\n",
    "Slide 1: Title slide\n",
    "- Title: \"Q3 2025 Results\"\n",
    "- Subtitle: \"Acme Corporation\"\n",
    "\n",
    "Slide 2: Revenue Overview\n",
    "- Title: \"Quarterly Revenue\"\n",
    "- Add a simple column chart showing:\n",
    "  - Q1: $12M\n",
    "  - Q2: $13M\n",
    "  - Q3: $14M\n",
    "\n",
    "Use clean, professional formatting.\n",
    "\"\"\",\n",
    "        }\n",
    "    ],\n",
    "    betas=[\"code-execution-2025-08-25\", \"files-api-2025-04-14\", \"skills-2025-10-02\"],\n",
    ")\n",
    "\n",
    "print(\"PowerPoint Response:\")\n",
    "print(\"=\" * 80)\n",
    "for content in pptx_response.content:\n",
    "    if content.type == \"text\":\n",
    "        print(content.text)\n",
    "\n",
    "print(\"\\n\\n📊 Token Usage:\")\n",
    "print(f\"   Input: {pptx_response.usage.input_tokens}\")\n",
    "print(f\"   Output: {pptx_response.usage.output_tokens}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download the PowerPoint File"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Download the PowerPoint file\n",
    "file_ids = extract_file_ids(pptx_response)\n",
    "\n",
    "if file_ids:\n",
    "    results = download_all_files(\n",
    "        client, pptx_response, output_dir=str(OUTPUT_DIR), prefix=\"q3_review_\"\n",
    "    )\n",
    "\n",
    "    print_download_summary(results)\n",
    "\n",
    "    print(\"\\n✅ Open the presentation in PowerPoint or Google Slides to view!\")\n",
    "else:\n",
    "    print(\"❌ No files found in response\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**⏱️ Note**: PDF generation typically takes **1-2 minutes** for simple documents. The cell will show `[*]` while running - be patient!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: PDF Documents\n",
    "\n",
    "#### Simple Example (1 line)\n",
    "```python\n",
    "# Quick PDF generation\n",
    "prompt = \"Create a professional invoice PDF for $500 consulting services\"\n",
    "```\n",
    "\n",
    "#### Detailed Example: Receipt\n",
    "**Note**: This is intentionally kept simple to ensure clean formatting."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: Simple Receipt\n",
    "\n",
    "**Note**: This is intentionally kept simple to ensure clean formatting."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a PDF receipt\n",
    "pdf_response = client.beta.messages.create(\n",
    "    model=MODEL,\n",
    "    max_tokens=4096,\n",
    "    container={\"skills\": [{\"type\": \"anthropic\", \"skill_id\": \"pdf\", \"version\": \"latest\"}]},\n",
    "    tools=[{\"type\": \"code_execution_20250825\", \"name\": \"code_execution\"}],\n",
    "    messages=[\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"\"\"Create a simple receipt PDF:\n",
    "\n",
    "RECEIPT\n",
    "\n",
    "Acme Corporation\n",
    "Date: January 15, 2025\n",
    "Receipt #: RCT-2025-001\n",
    "\n",
    "Customer: Jane Smith\n",
    "\n",
    "Items:\n",
    "- Product A: $50.00\n",
    "- Product B: $75.00\n",
    "- Product C: $25.00\n",
    "\n",
    "Subtotal: $150.00\n",
    "Tax (8%): $12.00\n",
    "Total: $162.00\n",
    "\n",
    "Thank you for your business!\n",
    "\n",
    "Use simple, clean formatting with clear sections.\n",
    "\"\"\",\n",
    "        }\n",
    "    ],\n",
    "    betas=[\"code-execution-2025-08-25\", \"files-api-2025-04-14\", \"skills-2025-10-02\"],\n",
    ")\n",
    "\n",
    "print(\"PDF Response:\")\n",
    "print(\"=\" * 80)\n",
    "for content in pdf_response.content:\n",
    "    if content.type == \"text\":\n",
    "        print(content.text)\n",
    "\n",
    "print(\"\\n\\n📊 Token Usage:\")\n",
    "print(f\"   Input: {pdf_response.usage.input_tokens}\")\n",
    "print(f\"   Output: {pdf_response.usage.output_tokens}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download and Verify the PDF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Download the PDF file\n",
    "file_ids = extract_file_ids(pdf_response)\n",
    "\n",
    "if file_ids:\n",
    "    results = download_all_files(\n",
    "        client, pdf_response, output_dir=str(OUTPUT_DIR), prefix=\"receipt_\"\n",
    "    )\n",
    "\n",
    "    print_download_summary(results)\n",
    "\n",
    "    # Verify PDF integrity\n",
    "    for result in results:\n",
    "        if result[\"success\"]:\n",
    "            file_path = result[\"output_path\"]\n",
    "            file_size = result[\"size\"]\n",
    "\n",
    "            # Basic PDF validation\n",
    "            with open(file_path, \"rb\") as f:\n",
    "                header = f.read(5)\n",
    "                if header == b\"%PDF-\":\n",
    "                    print(f\"\\n✅ PDF file is valid: {file_path}\")\n",
    "                    print(f\"   File size: {file_size / 1024:.1f} KB\")\n",
    "                else:\n",
    "                    print(f\"\\n⚠️ File may not be a valid PDF: {file_path}\")\n",
    "else:\n",
    "    print(\"❌ No files found in response\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Troubleshooting {#troubleshooting}\n",
    "\n",
    "### Common Issues and Solutions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Issue 1: API Key Not Found\n",
    "\n",
    "**Error:**\n",
    "```\n",
    "ValueError: ANTHROPIC_API_KEY not found\n",
    "```\n",
    "\n",
    "**Solution:**\n",
    "1. Ensure `.env` file exists in the parent directory\n",
    "2. Check that `ANTHROPIC_API_KEY=sk-ant-api03-...` is set\n",
    "3. Restart the Jupyter kernel after creating/editing `.env`\n",
    "\n",
    "### Issue 2: Container Parameter Not Recognized\n",
    "\n",
    "**Error:**\n",
    "```\n",
    "TypeError: Messages.create() got an unexpected keyword argument 'container'\n",
    "```\n",
    "\n",
    "**Solution:**\n",
    "Use `client.beta.messages.create()` instead of `client.messages.create()`:\n",
    "```python\n",
    "# ✅ Correct - use beta.messages\n",
    "response = client.beta.messages.create(\n",
    "    model=MODEL,\n",
    "    container={\"skills\": [...]},\n",
    "    tools=[{\"type\": \"code_execution_20250825\", \"name\": \"code_execution\"}],\n",
    "    messages=[...],\n",
    "    betas=[\"code-execution-2025-08-25\", \"files-api-2025-04-14\", \"skills-2025-10-02\"]\n",
    ")\n",
    "\n",
    "# ❌ Incorrect - regular messages doesn't support container\n",
    "response = client.messages.create(\n",
    "    model=MODEL,\n",
    "    container={\"skills\": [...]},  # Error!\n",
    "    messages=[...]\n",
    ")\n",
    "```\n",
    "\n",
    "### Issue 3: Skills Beta Requires Code Execution Tool\n",
    "\n",
    "**Error:**\n",
    "```\n",
    "BadRequestError: Skills beta requires the code_execution tool to be included in the request.\n",
    "```\n",
    "\n",
    "**Solution:**\n",
    "When using Skills, you MUST include the code_execution tool:\n",
    "```python\n",
    "# ✅ Correct\n",
    "response = client.beta.messages.create(\n",
    "    model=MODEL,\n",
    "    tools=[{\"type\": \"code_execution_20250825\", \"name\": \"code_execution\"}],\n",
    "    messages=[...],\n",
    "    betas=[\"...\", \"skills-2025-10-02\"]\n",
    ")\n",
    "\n",
    "# ❌ Incorrect - missing code_execution tool\n",
    "response = client.beta.messages.create(\n",
    "    model=MODEL,\n",
    "    messages=[...],\n",
    "    betas=[\"...\", \"skills-2025-10-02\"]\n",
    ")\n",
    "```\n",
    "\n",
    "### Issue 4: No Files Found in Response\n",
    "\n",
    "**Error:**\n",
    "```\n",
    "❌ No files found in response\n",
    "```\n",
    "\n",
    "**Solution:**\n",
    "1. Check that code execution tool is included in the request\n",
    "2. Verify the skill was loaded (check response content)\n",
    "3. Ensure the task actually requires file creation\n",
    "4. Look for error messages in the response text\n",
    "\n",
    "### Issue 5: File Download Failed\n",
    "\n",
    "**Error:**\n",
    "```\n",
    "Error retrieving file: File not found\n",
    "```\n",
    "\n",
    "**Solution:**\n",
    "1. Files may have a limited lifetime on Anthropic's servers\n",
    "2. Download files immediately after creation\n",
    "3. Check file_id is correctly extracted from response\n",
    "4. Verify Files API beta is included in betas list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Token Optimization Tips\n",
    "\n",
    "1. **Use \"latest\" version** for Anthropic skills - automatically optimized\n",
    "2. **Batch operations** - Create multiple files in one conversation when possible\n",
    "3. **Reuse containers** - Use `container.id` from previous responses to avoid reloading skills\n",
    "4. **Be specific** - Clear instructions mean fewer iterations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### API Rate Limiting\n",
    "\n",
    "If you encounter rate limits:\n",
    "- Implement exponential backoff for retries\n",
    "- Use batch processing for multiple files\n",
    "- Consider upgrading your API tier for higher limits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Next Steps\n\n🎉 **Congratulations!** You've learned the basics of Claude Skills.\n\n### See Skills in Action\n\nCheck out the official announcement to see how these Skills power Claude's file creation capabilities:\n- **[Claude Creates Files](https://www.anthropic.com/news/create-files)** - See how Skills enable Claude to create and edit Excel, PowerPoint, and PDF files directly\n\n### Continue Learning:\n\n- **[Notebook 2: Financial Applications](02_skills_financial_applications.ipynb)** - Real-world business use cases with financial data\n- **[Notebook 3: Custom Skills Development](03_skills_custom_development.ipynb)** - Build your own specialized skills\n\n### Support Articles:\n\n- 📚 **[Teach Claude your way of working using Skills](https://support.claude.com/en/articles/12580051-teach-claude-your-way-of-working-using-skills)** - User guide for working with Skills\n- 🛠️ **[How to create a skill with Claude through conversation](https://support.claude.com/en/articles/12599426-how-to-create-a-skill-with-claude-through-conversation)** - Interactive skill creation guide\n\n### Resources:\n\n- [Claude API Documentation](https://docs.anthropic.com/en/api/messages)\n- [Skills Documentation](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview)\n- [Skills Best Practices](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices)\n- [Files API Documentation](https://docs.claude.com/en/api/files-content)\n- [Claude Support](https://support.claude.com)\n\n### Try These Experiments:\n\n1. Start with simple one-line prompts to see Skills in action\n2. Modify the budget example to include more categories\n3. Create a presentation with your own data\n4. Generate a PDF report combining text and tables\n5. Use multiple skills together in a single request"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}